import 'dart:io';
import 'dart:math';

import 'package:demo_xm/common/ApiConfig.dart';
import 'package:demo_xm/model/Users.dart';
import 'package:demo_xm/model/base_bean.dart';
import 'package:flutter/material.dart';
import 'package:demo_xm/ui/base/TittleWidget.dart';
import 'dart:convert';

import '../../../../model/user.dart';

class PhoneLoginWidget extends StatefulWidget {
  const PhoneLoginWidget({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return PhoneLoginState();
  }
}

class PhoneLoginState<AccountLoginWidget> extends State {
  TextEditingController phoneController = TextEditingController();
  bool showCancel = true;
  bool canClickSend = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    phoneController.addListener(() {
      var text = phoneController.text;
      setState(() {
        showCancel = !text.isNotEmpty;
        canClickSend = text.length > 10;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: false,
      appBar: AppBar(
        backgroundColor: Colors.white,
        toolbarHeight: 0,
      ),
      backgroundColor: Colors.white,
      body: Column(
        children: [
          const TitleWidget("手机号登陆"),
          Expanded(
              child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                padding: const EdgeInsetsDirectional.only(top: 60),
                child: const Image(
                    width: 100,
                    height: 100,
                    image: AssetImage("images/home/ic_head_bg.png")),
              ),
              Container(
                  padding: const EdgeInsetsDirectional.only(
                      top: 40, start: 40, end: 40),
                  child: Stack(
                    alignment: Alignment.center,
                    fit: StackFit.loose,
                    children: [
                      TextField(
                          textAlign: TextAlign.center,
                          decoration: const InputDecoration(
                            hintText: "请输入手机号 （无需注册）",
                          ),
                          keyboardType: TextInputType.phone,
                          controller: phoneController),
                      Positioned(
                          right: -10,
                          child: Offstage(
                            offstage: showCancel,
                            child: IconButton(
                                onPressed: () {
                                  _deleleInput();
                                },
                                icon: const Image(
                                    image: AssetImage(
                                        "images/home/ic_cancel.png"))),
                          ))
                    ],
                  )),
              Container(
                padding: const EdgeInsetsDirectional.only(top: 12),
                child: Center(
                  child: TextButton(
                    onPressed: () {
                      if (canClickSend) {
                        _testQuery();
                      }else{
                        print("cancle input 11 length");
                      }
                    },
                    child: Text("获取验证码", style: getVerityColor()),
                  ),
                ),
              )
            ],
          ))
        ],
      ),
    );
  }

  TextStyle getVerityColor() {
    return TextStyle(
        color: canClickSend ? Color(0xff548DC1) : Color(0xff8A8A8F),
        fontSize: 16);
  }

  void _deleleInput() {
    setState(() {
      phoneController.text = "";
      _testPrintJson();
      // _testQuery();
    });
  }

  void _testPrintJson() {
    _decodeUsers();
  }

  User? _decodeUsers() {
    String msgJson = '{"name":"123","age":25}';
    var decode = json.decode(msgJson);
    var users = User.fromJson(decode);
    print("name:${users.name} age:${users.age}");
    return users;
  }


  void _testQuery() async {
    HttpClient client = HttpClient();

    var params = ApiConfig.getBaseParamsMap();
    params["type"] = '1';
    params["mobile"] = '18027884568';

    Uri uri = Uri(
        scheme: "https",
        host: ApiConfig.BASE_HOST,
        path: ApiConfig.GET_SMS_CODE);
    var clientRequest = await client.postUrl(uri);

    clientRequest.add(utf8.encode(json.encode(params)));
    var httpClientResponse = await clientRequest.close();
    var responMsg = await httpClientResponse.transform(utf8.decoder).join();
    print("responMsg ${responMsg}");
    var baseBeanEntity = BaseBean.fromJson(json.decode(responMsg));
    print(
        "baseBeanEntity code:${baseBeanEntity.code} msg:${baseBeanEntity.message}");
  }
}
